package org.t236.zuul;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.util.StringUtils;
import org.t236.commons.model.AjaxResult;

import java.util.Arrays;
import java.util.List;

public class IpFilter extends ZuulFilter {
    private List<String> blackIpList = Arrays.asList("127.0.0.1");

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        String remoteAddr = ctx.getRequest().getRemoteAddr();
        if(StringUtils.hasText(remoteAddr) && blackIpList.contains(remoteAddr)) {
            ctx.setSendZuulResponse(false);
            ctx.getResponse().setContentType("application/json;charset=UTF-8");
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                ctx.setResponseBody(objectMapper.writeValueAsString(AjaxResult.error("非法请求")));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}
